from __future__ import absolute_import
import logging
from os.path import join
from forest.api import Command, get_tool

logger = logging.getLogger('forest.commands.KeyboardLayout')

class KeyboardLayout(Command):
    ''' sets the keybord layout and other keyboard parameters.

        Example::

            keyboard:
                layout: us

        .. describe:: keyboard.layout

            Sets the keyboard layout.

        .. describe:: keyboard.keytable

            Sets the keyboard table. Defaults to the value of keyboard.layout.

        .. describe:: keyboard.model

            Sets the keyboard model. Defaults it to pc105+inet.
    '''
    __register__ = 'commands.setup.KeyboardLayout'

    requires_config = ['keyboard']

    def run(self, config):

        self.args = config.get('keyboard')

        if not self.args:
            return

        layout = self.args.get('layout', None)
        kb_path = config.join_install_root('etc', 'sysconfig', 'keyboard')

        layout_cfg = []
        if layout is not None: # specify everything or just 'name'
            layout_cfg = ['KEYTABLE="{0}"'.format(layout),
            'LAYOUT="{0}"'.format(layout)]

        add_model = True
        for key, val in self.args.iteritems():
            if key not in ['$command', 'layout']  or (layout is not None
                and key not in ['KEYTABLE', 'LAYOUT', '$command', 'layout']):

                layout_cfg.append('{0}="{1}"'.format(key, val))

            #avoiding double pass
            if key == 'MODEL':
                add_model = False

        if add_model:  # sane default
            layout_cfg.append('MODEL="pc105+inet"')

        layout_cfg.append('')
        get_tool('files.write')(kb_path, '\n'.join(layout_cfg))
